package cn.hl.hm.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection; 
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.GZIPOutputStream;

import javax.net.ssl.HttpsURLConnection;
  
public class NetUtil {
	//
	final static int MAX_CONNECT_TIMEOUT = 60000;
	final static int MAX_IO_TIMEOUT = 60000;
	//
	public final static int SUCCSS_RESP_CODE = 200;
	/**
	 * 
	 * @param srcUrl
	 * @param encode
	 * @return
	 */
	public static NetRsp netInput (String srcUrl,String encode) {
	
		NetRsp nr = new NetRsp();
		URL url = null;
		InputStream is = null;
		BufferedReader breader = null;
		HttpURLConnection conn = null;
		StringBuffer sb = new StringBuffer();
		try {
			url = new URL(srcUrl);
			System.out.println(srcUrl);
			// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("112.25.34.2", 80));  
			conn = (HttpURLConnection) url.openConnection( );
			conn.setConnectTimeout(MAX_CONNECT_TIMEOUT);// ���ӳ�ʱ ��λ����
			conn.setReadTimeout(MAX_IO_TIMEOUT);// ��ȡ��ʱ ��λ����
			//
			int respCode = conn.getResponseCode();
			System.out.println(respCode);
			if (respCode == SUCCSS_RESP_CODE)
			{
				is = conn.getInputStream();
				breader = new BufferedReader(new InputStreamReader(is, encode));
				String line = null;
				while((line = breader.readLine())!= null){
					sb.append(line +"\n");
				}
			}
			nr.setContent( sb.toString() );
			nr.setStatusCode(respCode);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if(breader!=null){
				breader.close();
				}
				if(is!=null){
					is.close();
				}
				if(conn != null){
					conn.disconnect();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return nr;
	}
	/**
	 * 
	 * @param srcUrl
	 * @param encode
	 * @return
	 * @throws Exception
	 */
	public  static NetRsp netInputSsl(String srcUrl,String encode) throws Exception{
		URL url = null;
		NetRsp nr = new NetRsp();
		InputStream is = null;
		BufferedReader breader = null;
		HttpsURLConnection conn = null;
		StringBuffer sb = new StringBuffer();
		try {
			url = new URL(srcUrl); 
			conn = (HttpsURLConnection) url.openConnection();
			conn.setConnectTimeout(MAX_CONNECT_TIMEOUT);// ���ӳ�ʱ ��λ����
			conn.setReadTimeout(MAX_IO_TIMEOUT);// ��ȡ��ʱ ��λ����
			int respCode = conn.getResponseCode();
			//
			if (respCode == SUCCSS_RESP_CODE)
			{
				is = conn.getInputStream();
				breader = new BufferedReader(new InputStreamReader(is, encode));
				String line = null;
				while((line = breader.readLine())!= null){
					sb.append(line +"\n"); 
				}
			}
			
			nr.setContent( sb.toString() );
			nr.setStatusCode(respCode);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				if(breader!=null){
				breader.close();
				}
				if(is!=null){
					is.close();
				}
				if(conn != null){
					conn.disconnect();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return nr;
        	
	} 
	
	/**
	 * 
	 * @param urlAddress
	 * @param paramMap
	 * @return
	 */
	public static String httpPost(String url,Map<String, String> paramMap){ 
        if(paramMap==null){ 
            paramMap = new HashMap<String, String>(); 
        } 
        String [] params = new String[paramMap.size()]; 
        int i = 0; 
        for(String paramKey:paramMap.keySet()){ 
            String param = paramKey+"="+paramMap.get(paramKey); 
            params[i] = param; 
            i++; 
        } 
        return httpPost(url, params); 
    } 
    
    public static String httpPost(String url,List<String> paramList){ 
        if(paramList==null){ 
            paramList = new ArrayList<String>(); 
        } 
        return httpPost(url, paramList.toArray(new String[0])); 
    } 
    
    public static String httpPost(String urlAddress,String []params){ 
        URL url = null; 
        HttpURLConnection con  =null; 
        BufferedReader in = null; 
        StringBuffer result = new StringBuffer(); 
        try { 
            url = new URL(urlAddress); 
            con  = (HttpURLConnection) url.openConnection(); 
            con.setUseCaches(false); 
            con.setDoOutput(true); 
            con.setRequestMethod("POST"); 
            String paramsTemp = ""; 
            for(String param:params){ 
                if(param!=null&&!"".equals(param.trim())){ 
                    paramsTemp+="&"+param; 
                } 
            } 
            System.out.println("paramsTemp:" + paramsTemp);
            byte[] b = paramsTemp.getBytes(); 
            con.getOutputStream().write(b, 0, b.length); 
            con.getOutputStream().flush(); 
            con.getOutputStream().close(); 
            in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
            while (true) { 
              String line = in.readLine(); 
              if (line == null) { 
                break; 
              } 
              else { 
                  result.append(line); 
              } 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }finally{ 
            try { 
                if(in!=null){ 
                    in.close(); 
                } 
                if(con!=null){ 
                    con.disconnect(); 
                } 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
        return result.toString(); 
    } 
    
    public static byte[] compress(String foo){
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    DeflaterOutputStream gzos = null; 
	    try {
	        gzos = new DeflaterOutputStream(baos);
	        gzos.write(foo.getBytes("UTF-8"));
	        gzos.flush();
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (gzos != null) try { gzos.close(); } catch (IOException ignore) {};
	    }

	    return baos.toByteArray();
	}
    
    
    public static byte[] gzip(String foo){
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    GZIPOutputStream gzos = null; 
	    try {
	        gzos = new GZIPOutputStream(baos);
	        gzos.write(foo.getBytes("UTF-8"));
	        gzos.flush();
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (gzos != null) try { gzos.close(); } catch (IOException ignore) {};
	    }

	    return baos.toByteArray();
	}
    /**
     * 
     * @param urlAddress
     * @param content
     * @return
     */
    public static String httpPost(String urlAddress,String content){ 
        URL url = null; 
        HttpURLConnection con  =null; 
        BufferedReader in = null; 
        StringBuffer result = new StringBuffer(); 
        try { 
            url = new URL(urlAddress); 
            con  = (HttpURLConnection) url.openConnection(); 
            con.setUseCaches(false); 
            con.setDoOutput(true);  
            
            con.setRequestProperty("Content-Type", "text/xml");
            con.setRequestProperty("compress", "true");
            con.setRequestMethod("POST");  
            //
            byte[] b =   content.getBytes();
            con.getOutputStream().write(b, 0, b.length); 
            con.getOutputStream().flush(); 
            con.getOutputStream().close(); 
            in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
            while (true) { 
              String line = in.readLine(); 
              if (line == null) { 
                break; 
              } 
              else { 
                  result.append(line); 
              } 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }finally{ 
            try { 
                if(in!=null){ 
                    in.close(); 
                } 
                if(con!=null){ 
                    con.disconnect(); 
                } 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
        return result.toString(); 
    } 
    
    public static String Send(String method, String url, String data)
	{
		HttpURLConnection conn = null;
		InputStream in = null;
		InputStreamReader isr = null;
		OutputStream out = null;
		StringBuffer result = null;
		try
		{ 
			URL u = new URL(url);
			conn = (HttpURLConnection) u.openConnection();
			conn.setRequestProperty("Accept-Encoding", "gzip");
			conn.setRequestProperty("Content-Type", "text/xml"); 
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(MAX_CONNECT_TIMEOUT);
			conn.setReadTimeout(MAX_IO_TIMEOUT);
			if(method.equals("POST")) {
				byte[] sendbyte = data.getBytes("UTF-8");
				out = conn.getOutputStream();
				out.write(sendbyte);
			}
			int status = conn.getResponseCode();
			if (status == 200)
			{
				String enc = conn.getContentEncoding();
				result = new StringBuffer();
				in = conn.getInputStream();
				enc = conn.getContentEncoding();
			
				if(enc != null && enc.equals("gzip")) {
					//System.out.println("\n\t\t\t\t\t\t------using gzip------\n");
					java.util.zip.GZIPInputStream gzin = new java.util.zip.GZIPInputStream(in);
					isr = new InputStreamReader(gzin, "UTF-8");
					
				} else {
					isr = new InputStreamReader(in, "UTF-8");
					//System.out.println("\n\t\t\t\t\t\t------NO gzip------\n");
				} 
				char[] c = new char[1024];
				int a = isr.read(c);
				while (a != -1)
				{
					result.append(new String(c, 0, a));
					a = isr.read(c);
				}
			} else {
				System.out.println("http code = " + status);	 
			} 
		} catch (MalformedURLException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			if (conn != null)
			{
				conn.disconnect();
			}
			try
			{
				if (in != null)
				{
					in.close();
				}
				if (isr != null)
				{
					isr.close();
				}
				if (out != null)
				{
					out.close();
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		} 
		return result == null ? null : result + "";
	}
    
    
	public static void main(String[] args){ 
		 String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
		 xml += "\n<AvailabilityRequestV2 siteid=\"1510419\" apikey=\"a784c97e-1fe8-4280-99f1-838e7dc0f62d\" async=\"false\" waittime=\"10\" xmlns=\"http://xml.agoda.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
		 xml +="\n<Type>6</Type>";
		 xml +="\n<Id>69668</Id>";
		 xml +="\n<Radius>0</Radius>";  
		 xml +="\n<Latitude>0</Latitude>";
		 xml +="\n<Longitude>0</Longitude>";	 
		 xml +="\n<CheckIn>2014-06-13</CheckIn>";
		 xml +="\n<CheckOut>2014-06-20</CheckOut>";
		 xml +="\n<Rooms>1</Rooms>";
		 xml +="\n<Adults>1</Adults>";
		 xml +="\n<Children>0</Children>";
		 xml +="\n<Rateplan>Retail</Rateplan>";
		 xml +="\n<Language>zh-cn</Language>";
		 xml +="\n<Currency>CNY</Currency>";
		 xml +="\n</AvailabilityRequestV2>";
		 List<String> list = new ArrayList<String>();
		 //
		 list.add("ID=1");
		 list.add("USERID=CXT117");
		 list.add("USERPWD=852159");
		 list.add("SENDTIME=GETDATE()");
		 list.add("CPNO=");
		 list.add("TASKID=0");
		 list.add("SVRTYPE=");
		 list.add("SENDLEVEL=9");
		 list.add("PHONES=15011231339");
		 list.add("MSGTYPE=11");
		 list.add("MSGTITLE=welcome");
		 list.add("MSGCONTENT=");
		 list.add("DEALSTATUS=0");
		 list.add("RESOURCEID=713121051000000001"); 
		 //
		System.out.println( httpPost("http://61.145.229.29:9016/mms_send_queue", list));
	}
}
